package com.czk.springcloud.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * feign实现令牌中继
 * 由于开起了服务降级时，远程调用其他微服务是新开的另外线程来调用的，请求的上下文信息都保存到ThreadLocal中，当切换线程时变量不能集成，所以需要将token
 * 从新绑定到header中
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/27 11:10
 */
@Component
public class BearerTokenRequestInterceptor implements RequestInterceptor {
    private static final Pattern BEARER_TOKEN_HEADER_PATTERN = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",
            Pattern.CASE_INSENSITIVE);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 拿到认证信息
        String authorization = HttpHeaders.AUTHORIZATION;
        // 强转
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)) {
            // 拿到认真头
            String header = requestAttributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
            if (header != null){
                // 判断是不是jwt_token
                Matcher matcher = BEARER_TOKEN_HEADER_PATTERN.matcher(header);
                if (matcher.matches()) {
                    // 清除token头 避免传染
                    requestTemplate.header(authorization);
                    requestTemplate.header(authorization, header);
                }
            }
        }
    }
}
